package com.example.demo.controller;

import com.example.demo.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/ai")
@CrossOrigin(origins = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS})
public class AiController {

    @Value("${ai.api.key:}")
    private String aiApiKey;

    @Value("${ai.api.url:https://api.siliconflow.cn/v1/chat/completions}")
    private String aiApiUrl;

    private final RestTemplate restTemplate = new RestTemplate();

    /**
     * 处理CORS预检请求
     */
    @RequestMapping(value = "/chat", method = RequestMethod.OPTIONS)
    public ResponseEntity<?> handleOptions() {
        return ResponseEntity.ok().build();
    }

    /**
     * 健康检查接口
     * @return 服务状态
     */
    @GetMapping("/health")
    public String health() {
        return "AI服务正常运行";
    }

    /**
     * 测试AI API配置
     * @return 配置信息
     */
    @GetMapping("/test")
    public String test() {
        return "AI API配置测试 - 密钥: " + (aiApiKey != null && !aiApiKey.isEmpty() ? "已配置" : "未配置");
    }

    /**
     * 简单测试接口
     */
    @GetMapping("/simple")
    public String simple() {
        return "简单测试接口正常工作";
    }

    /**
     * AI对话接口
     * @param request 对话请求
     * @return AI响应
     */
    @PostMapping("/chat")
    public Result chat(@RequestBody Map<String, Object> request) {
        try {
            System.out.println("收到AI对话请求: " + request);
            
            // 检查API密钥
            if (aiApiKey == null || aiApiKey.trim().isEmpty()) {
                return Result.error("AI API密钥未配置");
            }

            // 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + aiApiKey);

            // 构建请求体 - 根据您提供的规范
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "deepseek-ai/DeepSeek-V3.2-Exp");
            requestBody.put("messages", request.get("messages"));
            requestBody.put("stream", false);
            requestBody.put("max_tokens", 2000);
            requestBody.put("thinking_budget", 3000);
            requestBody.put("min_p", 0.5);
            requestBody.put("stop", null);
            requestBody.put("temperature", 0.1);
            requestBody.put("top_p", 0.8);
            requestBody.put("top_k", 30);
            requestBody.put("frequency_penalty", 0.5);
            requestBody.put("n", 1);
            
            // 设置响应格式为JSON对象
            Map<String, Object> responseFormat = new HashMap<>();
            responseFormat.put("type", "json_object");
            requestBody.put("response_format", responseFormat);

            System.out.println("发送AI API请求到: " + aiApiUrl);
            System.out.println("请求体: " + requestBody);

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

            // 发送请求到AI API
            ResponseEntity<Map> response = restTemplate.exchange(
                aiApiUrl, 
                HttpMethod.POST, 
                entity, 
                Map.class
            );

            System.out.println("AI API响应状态: " + response.getStatusCode());
            System.out.println("AI API响应体: " + response.getBody());

            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                Map<String, Object> responseBody = response.getBody();
                
                // 检查是否有错误
                if (responseBody.containsKey("error")) {
                    return Result.error("AI API错误: " + responseBody.get("error"));
                }
                
                // 提取usage信息中的total_tokens
                Integer totalTokens = null;
                if (responseBody.containsKey("usage")) {
                    Map<String, Object> usage = (Map<String, Object>) responseBody.get("usage");
                    if (usage != null && usage.containsKey("total_tokens")) {
                        Object tokensObj = usage.get("total_tokens");
                        if (tokensObj instanceof Number) {
                            totalTokens = ((Number) tokensObj).intValue();
                        }
                    }
                }
                
                // 转换响应格式以匹配前端期望的格式
                Map<String, Object> result = new HashMap<>();
                if (responseBody.containsKey("choices") && 
                    ((java.util.List<?>) responseBody.get("choices")).size() > 0) {
                    
                    Map<String, Object> choice = (Map<String, Object>) 
                        ((java.util.List<?>) responseBody.get("choices")).get(0);
                    
                    if (choice.containsKey("message")) {
                        Map<String, Object> message = (Map<String, Object>) choice.get("message");
                        result.put("choices", new Object[]{
                            Map.of(
                                "text", message.get("content"),
                                "created", System.currentTimeMillis() / 1000
                            )
                        });
                    } else {
                        return Result.error("AI API响应格式错误: 缺少message字段");
                    }
                } else {
                    return Result.error("AI API响应格式错误: 缺少choices字段");
                }
                
                // 添加total_tokens到响应中
                if (totalTokens != null) {
                    result.put("total_tokens", totalTokens);
                }
                
                return Result.success(result);
            } else {
                return Result.error("AI API调用失败，状态码: " + response.getStatusCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("AI服务暂时不可用: " + e.getMessage());
        }
    }
}
